package com.huanxiao.base.util;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;


import com.huanxiao.util.CtxHelper;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;


public class FileHelper {
    /**
     * 读取文件的内容
     *
     * @param filename 文件名称
     * @return
     * @throws IOException
     */
    public static String readFile(String filename) throws IOException {
        return new String(readBytes(filename));
    }

    public static byte[] readBytes(String filename) throws IOException {
        // 获得输入流
        File file = new File(filename);
        FileInputStream inStream = new FileInputStream(file);
        // new一个缓冲区
        byte[] buffer = new byte[1024];
        int len = 0;
        // 使用ByteArrayOutputStream类来处理输出流
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while ((len = inStream.read(buffer)) != -1) {
            // 写入数据
            outStream.write(buffer, 0, len);
        }
        // 得到文件的二进制数据
        byte[] data = outStream.toByteArray();
        // 关闭流
        outStream.close();
        inStream.close();
        return data;
    }

    /**
     * 以默认私有方式保存文件内容，存放在手机存储空间中
     *
     * @param filename
     * @param content
     * @throws IOException
     * @throws Exception
     */
    public static void save(String filename, String content) throws IOException {
        File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }

        FileOutputStream outStream = new FileOutputStream(file);
        outStream.write(content.getBytes());
        outStream.close();
    }

    public static void save(String filename, ByteArrayOutputStream stream) throws Exception {
        File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream outStream = new FileOutputStream(file);
        outStream.write(stream.toByteArray());
        outStream.close();
    }

    public static void copyAssets(String nameInAssets, String toPath) {
        AssetManager assetManager = CtxHelper.getApp().getAssets();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(nameInAssets);
            out = new FileOutputStream(toPath);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (IOException e) {
            Log.e("tag", "Failed to copy asset file: " + nameInAssets, e);
        }
    }

    public static void saveObject(String filename, Serializable s) throws Exception {
        File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream outStream = new FileOutputStream(file);
        ObjectOutputStream os = new ObjectOutputStream(outStream);
        os.writeObject(s);
        os.close();
    }

    public static Object loadObject(String filename) throws Exception {
        File file = new File(filename);
        if (!file.exists()) {
            return null;
        }

        FileInputStream inStream = new FileInputStream(file);
        ObjectInputStream is = new ObjectInputStream(inStream);
        Object ret = is.readObject();
        is.close();
        return ret;
    }

    public static boolean copyFile(String fromPath, String toPath) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(fromPath);
            out = new FileOutputStream(toPath);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
            return true;
        } catch (IOException e) {
            Log.e("tag", "Failed to copy file: " + fromPath, e);
            return false;
        }
    }

    public static void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }

    /**
     * 获取文件夹大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    public long getFileSize(File file) {
        long size = 0;
        File flist[] = file.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    /**
     * 删除文件夹中的文件
     *
     * @param file
     */
    public static void deleteFolderFile(File file, boolean isRoot) {
        try {
            if (file.isDirectory()) {// 如果是文件夹
                File flist[] = file.listFiles();
                for (int i = 0; i < flist.length; i++) {
                    deleteFolderFile(flist[i], false);
                }
            } else {
                if (!isRoot) {
                    file.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 图片转成string
     *
     * @param bitmap
     * @return
     */
    public static String convertBitmapToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
        byte[] appicon = baos.toByteArray();// 转为byte数组
        return Base64.encodeToString(appicon, Base64.DEFAULT);

    }

    /**
     * string转成bitmap
     *
     * @param st
     */
    public static Bitmap convertStringToBitmap(String st) {
        // OutputStream out;
        Bitmap bitmap = null;
        try {
            // out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(st, Base64.DEFAULT);
            bitmap =
                    BitmapFactory.decodeByteArray(bitmapArray, 0,
                            bitmapArray.length);
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 保存bitmap到文件
     *
     * @param bitmap
     * @param fileName
     */
    public static void saveBitmapToFile(Bitmap bitmap, String fileName) {
        File file = new File(PathHelper.getLocalProductImagePath(), fileName);//将要保存图片的路径
        if (file.exists()) {
            file.delete();
        }
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}